using System;
using Microsoft.SPOT;
using System.Threading;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.NetduinoPlus;
using System.Collections;

namespace Netduino.Sensor.Data
{
    /// <summary>
    /// A collector for data from the Netduino inputs
    /// </summary>
    public class Collector
    {
        /// <summary>
        /// The currently collected data, which is a list of ISample objects.
        /// </summary>
        public ArrayList Data { get; private set; }

        /// <summary>
        /// Creates a new collector, that immediately start to 
        /// collect new data on all it's registered sensors 
        /// in the background.
        /// Most recent data is available thru the Data property
        /// </summary>
        internal Collector()
        {
            Start(); //imediately
        }

        /// <summary>
        /// Starts collecting data
        /// </summary>
        private void Start()
        {
            ThreadStart collectMethod = new ThreadStart(Collect);
            Thread collectorThread = new Thread(collectMethod);
            collectorThread.Start();        // start background thread
        }

        /// <summary>
        /// Synchronously collects new data in a loop. This method runs on a background thread.
        /// </summary>
        private void Collect()
        {
            while (true)
            {
                if (_sensors != null) //we have any sensors yet?
                {
                    var data = new ArrayList();
                    foreach (ISensor sensor in _sensors)
                    {
                        data.Add(sensor.Take());
                    }
                    Data = data;
                    //Debug.Print(Data.ToString());
                    Thread.Sleep(500); //collect periodically
                }
            }
        }

        /// <summary>
        /// List of sensors to query for data.
        /// </summary>
        private ArrayList _sensors = new ArrayList();

        /// <summary>
        /// Adds the specified sensor to the stack of sensors to query for data.
        /// </summary>
        /// <param name="sensor"></param>
        internal void Add(ISensor sensor)
        {
            _sensors.Add(sensor);
        }
    }
}
